﻿using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DLL;
using NursingFormSystem.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;

namespace NursingFormSystem.TemplateSing
{
    public partial class AddTemplateSing : Form
    {
        #region 变量声明
        public NursingFormSystem.NurFormsService.NursingForm formService = new NursingFormSystem.NurFormsService.NursingForm();

        Tb_User LoginUser =  new Tb_User();
        //PatientInfo PatientInfo;
        //DataTable PathInfo = new DataTable();    //列表页标题行
        RepositoryItemCheckEdit chkedit = new RepositoryItemCheckEdit();
        #endregion

        #region 构造函数
        public AddTemplateSing(string[] loginUser)
        {
            InitializeComponent();
            //成员变量
            LoginUser.UserId = loginUser[0];     //工号
            LoginUser.UserName = loginUser[1];    //姓名
            LoginUser.DepartmentCode = loginUser[2];    //科室ID
            LoginUser.DepartmentName = loginUser[3];     //科室名称
            LoginUser.JobTitle = loginUser[4];      //护士ID
            LoginUser.JobCode = loginUser[5];      //护士名称
            // PatientInfo = patientInfo;   PatientInfo patientInfo    Tb_User loginUser
            InitGridControl(null);
            //getMeasure();
            //bandedGridView1.OptionsSelection.MultiSelect = true;
            //bandedGridView1.OptionsSelection.MultiSelectMode = DevExpress.XtraGrid.Views.Grid.GridMultiSelectMode.CheckBoxRowSelect;
            //bandedGridView1.OptionsSelection.ShowCheckBoxSelectorInColumnHeader = DevExpress.Utils.DefaultBoolean.True;
            //gridView1.MouseDown += gridView1_MouseDown;   //绑定行单机事件
            gridView1.RowClick += gridView1_RowClick;
        }
        #endregion
        
        #region 初始化表格控件,并取出数据
        /// <summary>
        /// 初始化表格控件
        /// </summary>
        private void InitGridControl(string templateType)
        {
            gridView1.OptionsCustomization.AllowSort = false;//不允许排序
            gridView1.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus;
            gridView1.OptionsView.ShowGroupPanel = false;//不显示组面板
            //gridView1.OptionsBehavior.Editable = false;//不允许编辑
            //gridView1.OptionsSelection.EnableAppearanceFocusedCell = false;//不允许单元格获得焦点
            gridView1.OptionsView.ColumnAutoWidth = false;
            gridView1.BestFitColumns();
            gridView1.HorzScrollVisibility = DevExpress.XtraGrid.Views.Base.ScrollVisibility.Always;
            gridView1.VertScrollVisibility = DevExpress.XtraGrid.Views.Base.ScrollVisibility.Always;
            gridView1.OptionsView.ShowFilterPanelMode = DevExpress.XtraGrid.Views.Base.ShowFilterPanelMode.Never;   //是否显示过滤面板
            gridView1.OptionsCustomization.AllowFilter = false;
            gridView1.Appearance.Row.Font = new Font("宋体", 11);
            memo_Text.Font = new Font("宋体", 11);
            //memo_Text.Height = 30;
            //gridView1.CustomRowCellEdit += gridView1_CustomRowCellEdit;
            //gridView1.CellMerge += gridView1_CellMerge;//行合并事件
            gridView1.MouseDown += gridView1_MouseDown;
            string select_sql = string.Empty;
            string DepartmentId = LoginUser.DepartmentCode;
            //string DepartmentName = LoginUser.DepartmentName;
            string UserId = LoginUser.UserId;
            //string NurseName = LoginUser.UserName;
           // string KnowledgeId = "";
            if (string.IsNullOrEmpty(templateType))
            {
                select_sql = "SELECT * FROM  [dbo].[NursingKnowledgeBase] ";
            }
            else 
            { 
            if (templateType.Equals("QY"))
            {
                select_sql = "SELECT * FROM  [dbo].[NursingKnowledgeBase] WHERE KnowledgeType = 'QY' ";
            }
            if (templateType.Equals("KS"))
            {
                select_sql = string.Format("SELECT * FROM  [dbo].[NursingKnowledgeBase] WHERE KnowledgeType = 'KS' and  DepartmentId = '{0}' ", DepartmentId);
            }
            if (templateType.Equals("GR"))
            {
                select_sql = string.Format("SELECT * FROM  [dbo].[NursingKnowledgeBase] WHERE KnowledgeType = 'GR' and NurseId = '{0}' ", UserId);
            }
            }
            DataTable dt = (SqlHelper.ExecuteDataset(select_sql, CommandType.Text)).Tables[0];
            DataTable dtt = new DataTable();
            dtt.Columns.Add(" ", System.Type.GetType("System.Boolean"));
            dtt.Columns[" "].SetOrdinal(0);
            //dtt.Columns.Add("ID", Type.GetType("System.String"));
            //dtt.Columns.Add("知识库分类ID", Type.GetType("System.String"));
            //dtt.Columns.Add("知识库分类名称", Type.GetType("System.String"));
            //dtt.Columns.Add("模板类型", Type.GetType("System.String"));
            //dtt.Columns.Add("科室ID", Type.GetType("System.String"));
            //dtt.Columns.Add("科室名称", Type.GetType("System.String"));
            //dtt.Columns.Add("病区ID", Type.GetType("System.String"));
            //dtt.Columns.Add("病区名称", Type.GetType("System.String"));
            //dtt.Columns.Add("护士ID", Type.GetType("System.String"));
            //dtt.Columns.Add("护士名称", Type.GetType("System.String"));
            dtt.Columns.Add("内容分类", Type.GetType("System.String"));
            //dtt.Columns.Add("内容", Type.GetType("System.String"));
            foreach (DataRow dr in dt.Rows)
            {
                dtt.Rows.Add(
                    false,
                //dr["ID"],
                //dr["KnowledgeId"],
                //dr["KnowledgeName"],
                //dr["KnowledgeType"],

                //dr["DepartmentId"],
                //dr["DepartmentName"],
                //dr["WardsId"],
                //dr["WardsName"],
                //dr["NurseId"],
                //dr["NurseName"],

                //dr["DepartmentId"] = LoginUser.DepartmentCode ,
                //dr["DepartmentName"] = LoginUser.DepartmentName,
                //dr["WardsId"] = LoginUser.DepartmentCode,
                //dr["WardsName"] = LoginUser.DepartmentName,
                //dr["NurseId"] = LoginUser.UserId ,
                //dr["NurseName"] = LoginUser.UserName,

                dr["ContentName"]
                //dr["KnowledgeContent"]
                    );
            }
            //dt.Columns.Add("ID", System.Type.GetType("System.String"));
            //dt.Columns.Add("知识库分类ID", Type.GetType("System.String"));
            //dt.Columns.Add("知识库分类名称", Type.GetType("System.String"));
            //dt.Columns.Add("模板类型", Type.GetType("System.String"));
            //dt.Columns.Add("科室ID", Type.GetType("System.String"));
            //dt.Columns.Add("科室名称", Type.GetType("System.String"));
            //dt.Columns.Add("病区ID", Type.GetType("System.String"));
            //dt.Columns.Add("病区名称", Type.GetType("System.String"));
            //dt.Columns.Add("护士ID", Type.GetType("System.String"));
            //dt.Columns.Add("护士名称", Type.GetType("System.String"));
            //dt.Columns.Add("内容分类", Type.GetType("System.String"));
            //dt.Columns.Add("内容", Type.GetType("System.String"));
            gridControl1.DataSource = dtt;
            //宽度调整
            gridView1.Columns[" "].MinWidth = 80;
            gridView1.Columns[" "].Width = 80;
            //gridView1.Columns["ID"].Width = 40;
            //gridView1.Columns["知识库分类ID"].Width = 80;
            //gridView1.Columns["知识库分类名称"].Width = 100;
            //gridView1.Columns["模板类型"].Width = 80;
            //gridView1.Columns["科室ID"].Width = 80;
            //gridView1.Columns["科室名称"].Width = 80;
            //gridView1.Columns["病区ID"].Width = 80;
            //gridView1.Columns["病区名称"].Width = 80;
            //gridView1.Columns["护士ID"].Width = 80;
            //gridView1.Columns["护士名称"].Width = 80;
            gridView1.Columns["内容分类"].MinWidth = 210;
            //gridView1.Columns["内容"].Width = 80;
            //不可编辑
            gridView1.Columns["内容分类"].OptionsColumn.AllowEdit = false;
            //gridView1.Columns["内容"].OptionsColumn.AllowEdit = false;
            //内容换行操作
            DevExpress.XtraEditors.Repository.RepositoryItemMemoEdit memoEditBigText = new DevExpress.XtraEditors.Repository.RepositoryItemMemoEdit();
            this.gridView1.Columns["内容分类"].ColumnEdit = memoEditBigText;
            //this.gridView1.Columns["内容"].ColumnEdit = memoEditBigText;
            //this.gridView1.Appearance.Row.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap;
            //对于行合并处理，先设置gridview的合并属性为true，再把不需要合并的列全部置为false，如下：
            gridView1.Columns[" "].OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False;
            //gridView1.Columns["知识库分类ID"].OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False;
            //gridView1.Columns["知识库分类名称"].OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False;
            //gridView1.Columns["模板类型"].OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False;
            //gridView1.Columns["科室ID"].OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False;
            //gridView1.Columns["科室名称"].OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False;
            //gridView1.Columns["病区ID"].OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False;
            //gridView1.Columns["病区名称"].OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False;
            //gridView1.Columns["护士ID"].OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False;
            //gridView1.Columns["护士名称"].OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False;
            gridView1.Columns["内容分类"].OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False;
            //gridView1.Columns["内容"].OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False;
            gridView1.CustomDrawColumnHeader += gridView1_CustomDrawColumnHeader;
            //gridControl1.DataSource = dtt;
            //InitGridData();
        }
        #endregion


        private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            string midValueStr = gridView1.GetDataRow(e.RowHandle)["内容分类"].ToString();
            var seleted = gridView1.GetDataRow(e.RowHandle)[" "].ToString();
            gridView1.GetDataRow(e.RowHandle)[" "] = seleted == "False" ? "True" : "False";
            seleted = gridView1.GetDataRow(e.RowHandle)[" "].ToString();
            if (seleted == "True") 
            {
                memo_Text.Text += midValueStr + ";";
            }
        }


        private void repositoryItemButtonEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            //判断点击的是哪一行的按钮，根据行的值，来进行跳转操作；保存成功之后要进行刷新操作
            int i = gridView1.GetFocusedDataSourceRowIndex();//获取所在的行号
        }

        #region 点击内容，复选框选上，并赋值到右边
        private void gridView1_CustomDrawColumnHeader(object sender, ColumnHeaderCustomDrawEventArgs e)
        {
            if (e.Column == (sender as GridView).Columns[" "])
            {
                e.Info.InnerElements.Clear();
                e.Info.Appearance.ForeColor = Color.Black;
                e.Painter.DrawObject(e.Info);
                DrawCheckBox(e.Graphics, e.Bounds, getCheckedCount() == gridView1.DataRowCount);
                e.Handled = true;
            }
        }
        #endregion
        

        private void gridView1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Clicks == 1 && e.Button == MouseButtons.Left)
            {
                GridHitInfo info;
                Point pt = gridView1.GridControl.PointToClient(Control.MousePosition);
                info = gridView1.CalcHitInfo(pt);

                if (info.InColumn && info.Column.FieldName == " ")
                {
                    if (getCheckedCount() == gridView1.DataRowCount)
                        UnChekAll();
                    else
                        CheckAll();
                }
            }

            DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo hInfo = gridView1.CalcHitInfo(new Point(e.X, e.Y));
            if (e.Button == MouseButtons.Left && e.Clicks == 1)
            {
                if (hInfo.InRow)//判断光标是否在行范围内 
                {
                    if (hInfo.Column != null && hInfo.Column.Name == "col")
                    {
                        string value = gridView1.GetDataRow(hInfo.RowHandle)[1] + "";
                        memo_Text.Text += value + ";";
                    }
                    else
                    {
                        //memo_Text.Text += "";
                      //  btn_Update_Click(null, null);
                    }
                }
            }
        }

        //private void gridView1_MouseDown(object sender, MouseEventArgs e)
        //{
        //    DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo hInfo = gridView1.CalcHitInfo(new Point(e.X, e.Y));
        //    if (e.Button == MouseButtons.Left && e.Clicks == 2)
        //    {
        //        if (hInfo.InRow)//判断光标是否在行范围内 
        //        {
        //            if (hInfo.Column != null && hInfo.Column.Name == "bandedGridColumn15")
        //            {
        //                string value = gridView1.GetDataRow(hInfo.RowHandle)[14] + "";
        //                Clipboard.SetDataObject(value);
        //                XtraMessageBox.Show("已复制到剪切板");
        //            }
        //            else
        //            {
        //                //btn_Update_Click(null, null);
        //            }
        //        }
        //    }
        //}

        private int getCheckedCount()
        {
            int count = 0;
            for (int i = 0; i < gridView1.DataRowCount; i++)
            {
                if ((bool)gridView1.GetRowCellValue(i, gridView1.Columns[" "]) == true) 
                    count++;
            }
            return count;
        }

        #region 勾选列全部选中
        /// <summary>
        /// 勾选列全部选中
        /// </summary>
        void CheckAll()
        {
            //for (int i = 0; i < gridView1.DataRowCount; i++)
            //{
            //    gridView1.SetRowCellValue(i, gridView1.Columns["勾选"], true);
            //}
        }
        #endregion

        #region 勾选列全部都不选中
        /// <summary>
        /// 勾选列全部都不选中
        /// </summary>
        void UnChekAll()
        {
            //for (int i = 0; i < gridView1.DataRowCount; i++)
            //{
            //    gridView1.SetRowCellValue(i, gridView1.Columns["勾选"], false);
            //}
        }
        #endregion

        #region 出现复选框
        protected void DrawCheckBox(Graphics g, Rectangle r, bool Checked)
        {
            //DevExpress.XtraEditors.ViewInfo.CheckEditViewInfo info;
            //DevExpress.XtraEditors.Drawing.CheckEditPainter painter;
            //DevExpress.XtraEditors.Drawing.ControlGraphicsInfoArgs args;
            //info = chkedit.CreateViewInfo() as DevExpress.XtraEditors.ViewInfo.CheckEditViewInfo;
            //painter = chkedit.CreatePainter() as DevExpress.XtraEditors.Drawing.CheckEditPainter;
            //info.EditValue = Checked;

            //info.Bounds = r;
            //info.PaintAppearance.ForeColor = Color.Black;
            //info.CalcViewInfo(g);
            //args = new DevExpress.XtraEditors.Drawing.ControlGraphicsInfoArgs(info, new DevExpress.Utils.Drawing.GraphicsCache(g), r);
            //painter.Draw(args);
            //args.Cache.Dispose();
        }
        #endregion
       
        #region 全院模板
        private void btn_TongYong_Click(object sender, EventArgs e)
        {
            InitGridControl("QY");
        }
        #endregion

        #region 科室模板
        private void btn_KeShi_Click(object sender, EventArgs e)
        {
            InitGridControl("KS");
        }
        #endregion

        #region 个人模板
        private void btn_GeRenMuBan_Click(object sender, EventArgs e)
        {
            InitGridControl("GR");
        }
        #endregion

        #region 确认
        private void btn_QueRen_Click(object sender, EventArgs e)
        {

        }
        #endregion

        #region 取消
        private void btn_QuXiao_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.OK;
        }
        #endregion

        #region 双击事件显示值到右边
        private void gridControl1_DoubleClick_1(object sender, EventArgs e)
        {
            DataTable dt = (gridControl1.DataSource as DataTable);
            int[] rownumber = this.gridView1.GetSelectedRows();//获取选中行号
            foreach (var rowIndex in rownumber)
            {
                DataRow row = dt.Rows[rowIndex];//根据行号获取相应行的数据
                memo_Text.Text += row["内容"].ToString() + ";";
            }
        }
        #endregion


        #region 三大模板
        private void radioGroup1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (radioGroup_MuBan.Text == "0") 
            {
                InitGridControl("QY");
            }
            else if (radioGroup_MuBan.Text == "1")
            {
                InitGridControl("KS");
            }
            else
            {
                InitGridControl("GR");
            }
        }
        #endregion
       


    }
}
